package repository

import (
	"gin_server/internal/model" // 请替换为实际的包路径
	"gin_server/internal/request" // 请替换为实际的包路径
	"gorm.io/gorm"
)

// GroupRepository 定义群组仓库接口
type GroupRepository interface {
	// Create 创建新群组
	Create(entity *model.Group) (*model.Group, error)
	// FindByID 根据ID查找群组
	FindByID(id uint) (*model.Group, error)
	// FindAll 获取所有群组列表
	FindAll(params *request.GroupQueryRequest) ([]*model.Group, int64, error)
	// Update 更新群组信息
	Update(id uint, entity *request.GroupUpdateRequest) error
	// Delete 软删除群组
	Delete(id uint) error
	// Restore 恢复群组
	Restore(id uint) error
	// ForceDelete 真删除群组
	ForceDelete(id uint) error
}

type groupRepository struct {
	db *gorm.DB
}

func NewGroupRepository(db *gorm.DB) GroupRepository {
	return &groupRepository{db: db}
}

func (r *groupRepository) Create(entity *model.Group) (*model.Group, error) {
	return entity, r.db.Create(entity).Error
}

func (r *groupRepository) FindByID(id uint) (*model.Group, error) {
	var entity model.Group
	err := r.db.First(&entity, id).Error
	return &entity, err
}

func (r *groupRepository) FindAll(params *request.GroupQueryRequest) ([]*model.Group, int64, error) {
	var entities []*model.Group
	var total int64

	query := r.db.Model(&model.Group{})

	if params != nil {
		// 应用查询条件
		if params.GroupId != nil {
			query = query.Where("group_id LIKE ?", "%"+*params.GroupId+"%")
		}
      if params.CreatorUid != nil {
			query = query.Where("creator_uid = ?", *params.CreatorUid)
		}
      if params.GroupName != nil {
			query = query.Where("group_name LIKE ?", "%"+*params.GroupName+"%")
		}
      if params.GroupStatus != nil {
			query = query.Where("group_status LIKE ?", "%"+*params.GroupStatus+"%")
		}
      if params.GroupStatus != nil {
			query = query.Where("group_status = ?", *params.GroupStatus)
		}
      
	}
	
	query.Count(&total)
	query.Order("create_time desc")
	err := query.Offset((params.Current - 1) * params.PageSize).Limit(params.PageSize).Find(&entities).Error
	return entities, total, err
}

func (r *groupRepository) Update(id uint, entity *request.GroupUpdateRequest) error {
	return r.db.Model(&model.Group{}).Where("id = ?", id).Updates(entity).Error
}

func (r *groupRepository) Delete(id uint) error {
	return r.db.Delete(&model.Group{}, id).Error
}

func (r *groupRepository) Restore(id uint) error {
	return r.db.Unscoped().Model(&model.Group{}).Where("id = ?", id).Update("delete_time", nil).Error
}

func (r *groupRepository) ForceDelete(id uint) error {
	return r.db.Unscoped().Delete(&model.Group{}, id).Error
}
